using System.Windows.Media;
using DimensionsHelper.Client.Helpers;
using DimensionsHelper.Common.Contracts;
using DimensionsHelper.Common.Contracts.Excel;
using DimensionsHelper.Common.Contracts.Excel.Options;
using DimensionsHelper.Common.TableFormatter;

namespace DimensionsHelper.Client.ViewModels.CsvFormatter;

public partial class FontStyleOptionsViewModel(IServiceProvider serviceProvider)
    : ObservableObject, IFontStyleOptions, IProjectOption<FontStyleOptions>
{
    private readonly CsvFormatterViewModel _reporter = serviceProvider.GetRequiredService<CsvFormatterViewModel>();


    [ObservableProperty]
    private Brush _fontColorBrush = Brushes.Black;


    [ObservableProperty]
    private FontFamilyInfo _fontFamily = FontFamilyHelper.DefaultFontFamily;


    [ObservableProperty]
    private double _fontSize = TableFormatterDefaultValues.FontSize;


    [ObservableProperty]
    private bool _bold;


    [ObservableProperty]
    private bool _italic;


    [ObservableProperty]
    private bool _underlined;


    [ObservableProperty]
    private UnderLineType _underLineType = DimensionsHelper.Common.Contracts.Excel.UnderLineType.Single;


    public FontStyleOptions GetOptionObject()
    {
        return new FontStyleOptions();
    }

    public bool TryWriteOption(FontStyleOptions target)
    {
        target.FontFamily = FontFamily.Name;
        target.FontSize = (float)FontSize;
        target.FontColor = ((SolidColorBrush)FontColorBrush).Color.ToExcelStyleColor();
        target.UnderLine = UnderLineType;

        if (Bold)
        {
            target.FontType |= FontType.Bold;
        }

        if (Underlined)
        {
            target.FontType |= FontType.Underline;
        }

        if (Italic)
        {
            target.FontType |= FontType.Italic;
        }

        return true;
    }

    public void LoadOption(FontStyleOptions source)
    {
        FontSize = source.FontSize;
        FontColorBrush = new SolidColorBrush(source.FontColor.ToColor());
        UnderLineType = source.UnderLine;
        Bold = source.FontType.HasFlag(FontType.Bold);
        Underlined = source.FontType.HasFlag(FontType.Underline);
        Italic = source.FontType.HasFlag(FontType.Italic);

        if (!FontFamilyHelper.TryGetFontFamilyInfo(source.FontFamily, out var family))
        {
            family = FontFamilyHelper.DefaultFontFamily;
            _reporter.ReportService?.Warn("'{0}'不是有效的字体名，修改为默认值'{1}'", source.FontFamily, family.Name);
        }

        FontFamily = family;
    }
}